package com.atguigu.test07;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author haoranlu
 * @project IntelliJ IDEA
 */
public class JDBCToolsV5 {
    private static DataSource ds;
    private static ThreadLocal<Connection> th;
    static {
           try {
               Properties pro = new Properties();
               pro.load(JDBCToolsV5.class.getClassLoader().getResourceAsStream("druid.properties"));
               ds = DruidDataSourceFactory.createDataSource(pro);
               th = new ThreadLocal<Connection>();
           }catch (Exception e){
               e.printStackTrace();
           }
    }
    public static Connection getConnection() throws SQLException {
        Connection conn = th.get();
        if(conn == null){
            conn = ds.getConnection();
            th.set(conn);
        }
        return conn;
    }
    public static void free(Connection conn){
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
